package com.tanhua.admin.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.tanhua.admin.service.AnalysisService;
import com.tanhua.model.domain.Everyday;
import com.tanhua.model.vo.AnalysisVo;
import com.tanhua.model.vo.DashboardUsersVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    private AnalysisService analysisService;


    /**
     * 首页概要统计信息
     * @return
     */
    @GetMapping("/summary")
    public ResponseEntity<AnalysisVo> summary(){
        //创建Vo对象
        AnalysisVo analysisVo = new AnalysisVo();
        //获取当前时间
        DateTime dateTime = DateTime.now();

        //为vo对象赋值
        //累计用户数量
        analysisVo.setCumulativeUsers(analysisService.sumCumulativeUsers());

        //过去30天活跃用户
        analysisVo.setActivePassMonth(analysisService.queryActiveUserCount(dateTime, -30));

        //过去7天活跃用户
        analysisVo.setActivePassWeek(analysisService.queryActiveUserCount(dateTime, -7));

        //今日新增用户
        analysisVo.setNewUsersToday(analysisService.queryRegisterUserCount(dateTime, 0));

        //今日登录次数
        analysisVo.setLoginTimesToday(analysisService.queryLoginUserCount(dateTime, 0));

        //今日活跃用户
        analysisVo.setActiveUsersToday(analysisService.queryActiveUserCount(dateTime, 0));

        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal regDecimal = computeRate(analysisVo.getNewUsersToday(),
                analysisService.queryRegisterUserCount(dateTime, -1));
        byte regByte = regDecimal.byteValue();
        Integer newUserComputeRate = Integer.valueOf(regByte);
        analysisVo.setNewUsersTodayRate(newUserComputeRate);


        //今日登录用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal logDecimal = computeRate(analysisVo.getLoginTimesToday(),
                analysisService.queryLoginUserCount(dateTime, -1));
        byte logByte = logDecimal.byteValue();
        Integer newLogComputeRate = Integer.valueOf(logByte);
        analysisVo.setNewUsersTodayRate(newLogComputeRate);

        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal activeDecimal = computeRate(analysisVo.getActiveUsersToday(),
                analysisService.queryActiveUserCount(dateTime, -1));
        byte activeByte = logDecimal.byteValue();
        Integer newActiveComputeRate = Integer.valueOf(activeByte);
        analysisVo.setNewUsersTodayRate(newActiveComputeRate);

        return ResponseEntity.ok(analysisVo);
    }


    /**
     * 统计图接口
     * @param type 类型 101为新增 102为活跃 103为次日留存率
     * @param sd 开始时间
     * @param ed 结束时间
     * @return DashboardUsersVo
     */
    @GetMapping("/users")
    public ResponseEntity<DashboardUsersVo> statistics(String type, String sd, String ed){
        String ssd = DateUtil.format(new Date(Long.parseLong(sd)), "yyyy-MM-dd");
        String eed = DateUtil.format(new Date(Long.parseLong(ed)), "yyyy-MM-dd");
        //判断type
        if ("101".equals(type)){
            //类型为101 新增用户统计查询
            //调用方法获取开始时间到结束时间之间的所有日期(String 类型)
            List<String> detHashList = getDetHashList(ssd, eed);
            //构建Vo对象
            DashboardUsersVo vo = new DashboardUsersVo();
            List<Everyday> thisYear = new ArrayList<>();
            for (String title : detHashList) {
                //创建Everyday对象
                Everyday everyday = new Everyday();
                everyday.setTitle(title);
                DateTime date = DateTime.parse(title);
                //调用接口查询时间段内的活跃用户数量
                Integer amount = analysisService.queryRegisterUserCount(date, 0);
                if (amount == null){
                    amount = 0;
                }
                everyday.setAmount(amount);
                thisYear.add(everyday);
            }
            vo.setThisYear(thisYear);
            //计算去年时间段内的统计量
            List<Everyday> lastVo = new ArrayList<>();
            for (String lastYear : detHashList) {
                Everyday everyday = new Everyday();
                cn.hutool.core.date.DateTime date = DateUtil.parse(lastYear);
                date = DateUtil.offsetMonth(date, -12);
                String format = DateUtil.format(date, "yyyy-MM-dd");
                DateTime dateTime = DateTime.parse(format);
                /*String substring = lastYear.substring(0, 4);
                int i = Integer.parseInt(substring);
                i = i - 1;
                String lastYearTitle = String.valueOf(i) + lastYear.substring(4, 6);
                everyday.setTitle(lastYearTitle);
                DateTime dateTime = DateTime.parse(lastYearTitle);*/
                Integer amount = analysisService.queryRegisterUserCount(dateTime, 0);
                if (amount == null){
                    amount = 0;
                }
                everyday.setAmount(amount);
                lastVo.add(everyday);
            }
            vo.setLastYear(lastVo);

            return ResponseEntity.ok(vo);
        }else if ("102".equals(type)){
            //类型为102 活跃用户统计查询
            //调用方法获取开始时间到结束时间之间的所有日期(String 类型)
            List<String> detHashList = getDetHashList(ssd, eed);
            //构建Vo对象
            DashboardUsersVo vo = new DashboardUsersVo();
            List<Everyday> thisYear = new ArrayList<>();
            for (String title : detHashList) {
                //创建Everyday对象
                Everyday everyday = new Everyday();
                everyday.setTitle(title);
                DateTime date = DateTime.parse(title);
                //调用接口查询时间段内的活跃用户数量
                Integer amount = analysisService.queryActiveUserCount(date, 0);
                if (amount == null){
                    amount = 0;
                }
                everyday.setAmount(amount);
                thisYear.add(everyday);
            }
            vo.setThisYear(thisYear);
            //计算去年时间段内的统计量
            List<Everyday> lastVo = new ArrayList<>();
            for (String lastYear : detHashList) {
                Everyday everyday = new Everyday();
                /*String substring = lastYear.substring(0, 4);
                int i = Integer.parseInt(substring);
                i = i - 1;
                String lastYearTitle = String.valueOf(i);
                String substring1 = lastYear.substring(4, 6);
                lastYearTitle = lastYearTitle + substring1;
                everyday.setTitle(lastYearTitle);
                DateTime dateTime = DateTime.parse(lastYearTitle);*/
                cn.hutool.core.date.DateTime date = DateUtil.parse(lastYear);
                date = DateUtil.offsetMonth(date, -12);
                String format = DateUtil.format(date, "yyyy-MM-dd");
                DateTime dateTime = DateTime.parse(format);
                Integer amount = analysisService.queryActiveUserCount(dateTime, 0);
                if (amount == null){
                    amount = 0;
                }
                everyday.setAmount(amount);
                lastVo.add(everyday);
            }
            vo.setLastYear(lastVo);

            return ResponseEntity.ok(vo);
        }else {
            //类型为103 次日留存率统计查询
            //调用方法获取开始时间到结束时间之间的所有日期(String 类型)
            List<String> detHashList = getDetHashList(ssd, eed);
            //构建Vo对象
            DashboardUsersVo vo = new DashboardUsersVo();
            List<Everyday> thisYear = new ArrayList<>();
            for (String title : detHashList) {
                //创建Everyday对象
                Everyday everyday = new Everyday();
                everyday.setTitle(title);
                DateTime date = DateTime.parse(title);
                //调用接口查询时间段内的活跃用户数量
                Integer amount = analysisService.queryRetention1d(date, 0);
                everyday.setAmount(amount);
                thisYear.add(everyday);
            }
            vo.setThisYear(thisYear);
            //计算去年时间段内的统计量
            List<Everyday> lastVo = new ArrayList<>();
            for (String lastYear : detHashList) {
                Everyday everyday = new Everyday();
                /*String substring = lastYear.substring(0, 4);
                int i = Integer.parseInt(substring);
                i = i - 1;
                String lastYearTitle = String.valueOf(i) + lastYear.substring(4, 6);
                everyday.setTitle(lastYearTitle);
                DateTime dateTime = DateTime.parse(lastYearTitle);*/
                cn.hutool.core.date.DateTime date = DateUtil.parse(lastYear);
                date = DateUtil.offsetMonth(date, -12);
                String format = DateUtil.format(date, "yyyy-MM-dd");
                DateTime dateTime = DateTime.parse(format);
                Integer amount = analysisService.queryRetention1d(dateTime, 0);
                everyday.setAmount(amount);
                lastVo.add(everyday);
            }
            vo.setLastYear(lastVo);

            return ResponseEntity.ok(vo);
        }

    }




    /**
     * 获取时间段内的所有日期集合
     * @param begin
     * @param end
     * @return
     */
    public static List getDetHashList(String begin, String end) {
        List hashList = new ArrayList<>();
        String btime = begin.substring(0, 10);//yyyy-MM-dd
        String etime = end.substring(0, 10);

        Date bDate = DateUtil.parse(btime, DatePattern.NORM_DATE_PATTERN);//yyyy-MM-dd
        Date eDate = DateUtil.parse(etime, DatePattern.NORM_DATE_PATTERN);
        List<cn.hutool.core.date.DateTime> dateList = DateUtil.rangeToList(bDate, eDate, DateField.DAY_OF_YEAR);//创建日期范围生成器
        String hash = null;
        for (cn.hutool.core.date.DateTime dt : dateList) {
            hash = dt.toString().substring(0, 10);;
            hashList.add(hash);
        }
        return hashList;
    }

    /**
     * 计算环比
     * @param current
     * @param last
     * @return
     */
    private static BigDecimal computeRate(Integer current, Integer last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }
}
